package com.pms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pms.dto.OwnerPageQueryDTO;
import com.pms.dto.OwnerSaveDTO;
import com.pms.dto.OwnerUpdateDTO;
import com.pms.entity.Building;
import com.pms.entity.Community;
import com.pms.entity.Owner;
import com.pms.mapper.BuildingMapper;
import com.pms.mapper.CommunityMapper;
import com.pms.mapper.OwnerMapper;
import com.pms.result.PageResult;
import com.pms.service.OwnerService;
import com.pms.vo.OwnerPageQueryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class OwnerServiceImpl implements OwnerService{

    @Autowired
    private OwnerMapper ownerMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private CommunityMapper communityMapper;

    /**
     * 新增业主
     * @param ownerSaveDTO
     */
    public void save(OwnerSaveDTO ownerSaveDTO) {
        Owner owner = new Owner();
        BeanUtils.copyProperties(ownerSaveDTO,owner);
        ownerMapper.insert(owner);

        // 修改对应楼栋的业主id
        Building building=buildingMapper.getById(ownerSaveDTO.getBuildingId());
        building.setOwnerId(owner.getId());
        building.setUpdateDate(LocalDate.now());
        buildingMapper.update(building);
    }

    /**
     * 业主分页查询
     * @param ownerPageQueryDTO
     * @return
     */
    public PageResult page(OwnerPageQueryDTO ownerPageQueryDTO) {
        PageHelper.startPage(ownerPageQueryDTO.getPage(), ownerPageQueryDTO.getPageSize());
        Page<OwnerPageQueryVO> page=ownerMapper.pageQuery(ownerPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据id批量删除
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            // 同时将关联的楼栋表中的业主id删除，其中状态设为 0：空闲中
            // 一个业主可能有多个楼栋,也可能暂时没有设置楼栋信息

            // 根据业主id查询楼栋
            List<Building> buildingList = buildingMapper.getByOwnerId(id);
            if(buildingList!=null){
                // 修改楼栋信息
                for (Building building : buildingList) {
                    building.setOwnerId(0);
                    building.setStatusId(0);
                    buildingMapper.update(building);
                }
            }

            ownerMapper.delete(id);
        }
    }

    /**
     * 修改业主信息
     * @param ownerUpdateDTO
     */
    public void update(OwnerUpdateDTO ownerUpdateDTO) {
        Owner owner = new Owner();
        BeanUtils.copyProperties(ownerUpdateDTO,owner);
        Community community=communityMapper.getByName(ownerUpdateDTO.getCommunityName());
        owner.setCommunityId(community.getId());
        ownerMapper.update(owner);
    }
}
